package com.srd.phone.activity;

import android.os.Bundle;
import android.view.View;

import com.shengrongdai.srd.R;
import com.srd.phone.utils.StorageUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 更新APP界面
 */
public class UpdateActivity extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update);
    }

    public void startView(View view) {
        pause = false;
        Thread thread = new Thread(runnable);
        thread.start();
    }

    public void pauseView(View view) {
        pause = true;
    }

    private boolean pause = false;
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            HttpURLConnection conn = null;
            InputStream input = null;
            RandomAccessFile raf = null;
            try {
                int contentLength = -1;
                File file = new File(StorageUtils.getFile(UpdateActivity.this), "android.apk");
                raf = new RandomAccessFile(file, "rwd");
                URL url = new URL("http://192.168.1.211:60099/android.apk");
                conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(2000);
                conn.setReadTimeout(2000);
                conn.setRequestMethod("GET");
                if (conn.getResponseCode() == 200) {
                    contentLength = conn.getContentLength();
                }
                conn.disconnect();
                conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(2000);
                conn.setReadTimeout(2000);
                conn.setRequestMethod("GET");
                conn.setRequestProperty("Range", "bytes=" + file.length() + "-" + contentLength); //是个闭合区间
                raf.seek(file.length());//表示指针开始位置
                if (conn.getResponseCode() == 206) { //206表示部分内容，跟range配合这用
                    input = conn.getInputStream();
                    byte[] buffer = new byte[1024 * 4];
                    int len = -1;
                    long currentLength = file.length();
                    while ((len = input.read(buffer)) != -1 && pause == false) {
                        raf.write(buffer, 0, len);
                        currentLength += len;

                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    input.close();
                    raf.close();
                    conn.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    };
}
